class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<List<Integer>> result = new ArrayList<>();
        queue.add(root);
        int x = 1; // 用于记录是多少层
        while (!queue.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.add(poll.left);
                if (poll.right != null) queue.add(poll.right);
                list.add(poll.val);
            }
            if (x % 2 == 0) {
                Stack<Integer> stack = new Stack<>();
                for (Integer integer : list) {
                    stack.push(integer);
                }
                list.clear();
                while (!stack.isEmpty()) {
                    list.add(stack.pop());
                }
            }
            result.add(list);
            x++; // 层数加一
        }
        return result;
    }
}